package com.dy.service.impl;

import cn.hutool.db.sql.Order;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.common.R;
import com.dy.entity.*;
import com.dy.mapper.OrdersMapper;
import com.dy.service.*;
import com.dy.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private OrderDetailService orderDetailService;
    /**
     * @Author dy
     * @Description: 生成订单
     */
    @Transactional
    public R<String> submit(Orders orders) {
        //获取当前用户信息
        Long userId = CurrentHolder.getCurrent();
        User user = userService.getById(userId);

        //获取地址信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if(addressBook == null){
            log.error("错误，为获取到地址信息。(ㄒoㄒ)~~");
            return R.error("错误，为获取到地址信息。(ㄒoㄒ)~~");
        }
        //获取购物车数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);
        if(list.isEmpty()){
            log.error("选物车还是空的，请先选择需要的商品。(ㄒoㄒ)~~");
            return R.error("选物车还是空的，请先选择需要的商品。(ㄒoㄒ)~~");
        }

        long orderId = IdWorker.getId();//订单号

        //获取总价钱 外加订单明细集合
        AtomicInteger amount = new AtomicInteger(0);
        List<OrderDetail> orderDetails = list.stream().map(item ->{
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());//number: 数量
            orderDetail.setDishFlavor(item.getDishFlavor());
            if(item.getDishId() != null){
                orderDetail.setDishId(item.getDishId());
            }else{
                orderDetail.setSetmealId(item.getSetmealId());
            }
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());//单价
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //生成订单号
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());//下单时间
        orders.setCheckoutTime(LocalDateTime.now());//结账时间
        orders.setStatus(2);  //订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setPayMethod(2);//支付方式 1微信，2支付宝
        //number :订单号
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        //向订单表插入数据，一条数据
        this.save(orders);
        //订单明细表 插入多条数据
        orderDetailService.saveBatch(orderDetails);
        //清楚购物车
        shoppingCartService.remove(queryWrapper);
        log.info("下单成功,订单号为：{}",orderId);
        return R.success("下单成功");
    }
}
